import paramiko
from paramiko.ssh_exception import SSHException

# 1. 服务器列表（替换为实际IP和密码）
servers = [
    {"ip": "10.130.1.124", "user": "root", "pwd": "Nesc@@000686"},
    {"ip": "10.130.1.80", "user": "root", "pwd": "Nesc@@000686"}
]

# 2. 单台服务器执行命令
def run_cmd_on_server(server, cmd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 自动接受未知主机密钥
    try:
        # 连接服务器
        ssh.connect(
            hostname=server["ip"],
            username=server["user"],
            password=server["pwd"],
            timeout=10
        )
        # 执行命令，获取输出
        stdin, stdout, stderr = ssh.exec_command(cmd)
        result = stdout.read().decode("utf-8")
        error = stderr.read().decode("utf-8")
        
        print(f"=== 服务器 {server['ip']} 执行结果 ===")
        print(result if result else error)
    except SSHException as e:
        print(f"服务器 {server['ip']} 连接失败：{str(e)}")
    finally:
        ssh.close()

# 3. 批量执行命令
if __name__ == "__main__":
    target_cmd = "ip a"  # 要执行的Linux命令
    for server in servers:
        run_cmd_on_server(server, target_cmd)